package cn.itcast.tanhua.mytanhuadubboservice.api;

import cn.hutool.core.util.ObjectUtil;
import cn.itcast.tanhua.enums.IdType;
import cn.itcast.tanhua.mytanhuadubbointerface.api.PeachApi;
import cn.itcast.tanhua.pojo.Sound;
import com.alibaba.dubbo.config.annotation.Service;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author 张钊煌
 * @since 2021/12/6 18:41
 */
@Service(version = "1.0.0")
@Slf4j
public class PeachApiImpl implements PeachApi {
    @Autowired
    private IdService idService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Sound receivePeach(Long userId) {

        List<Sound> all = this.mongoTemplate.findAll(Sound.class);

        for (Sound sound : all) {
            String result = this.redisTemplate.opsForValue().get("SOUND_" + sound.getSoundUrl() + "_" + userId);
            if(result == null && !userId.equals(sound.getUserId())){
                //标记该用户已经听过的语音
                this.redisTemplate.opsForValue().set("SOUND_" + sound.getSoundUrl() + "_" + userId, "1");
                //获取今日次数
                String countStr = this.redisTemplate.opsForValue().get("SOUND_COUNT" + userId);
                //记录今日次数
                if(countStr == null){
                    this.redisTemplate.opsForValue().set("SOUND_COUNT" + userId, "1", 1, TimeUnit.DAYS);
                }else{
                    int count = Integer.parseInt(countStr);
                    count++;
                    this.redisTemplate.opsForValue().set("SOUND_COUNT" + userId, count + "");
                }
                return sound;
            }
        }
        return null;

        /*//获取所有数据,排除本身数据
        Query queryCount =Query.query(Criteria.where("userId").nin(userId));
        List<Sound> soundList=mongoTemplate.findAll(Sound.class);
        int count=soundList.size();

        // 获取随机数
        Random random=new Random();
        int num = random.nextInt(count);

        // 获取录音文件
        Sound sound =soundList.get(num);

        Query query=Query.query(Criteria.where("userId").is(userId));
        SoundTime soundTime=mongoTemplate.findOne(query,SoundTime.class);

        Update update=Update.update("soundTime",soundTime.getSoundTime()-1);
        mongoTemplate.updateFirst(query, update, SoundTime.class);
        SoundTime soundTime1=mongoTemplate.findOne(query,SoundTime.class);

        SoundVo soundVo=new SoundVo();
        soundVo.setRemainingTimes(soundTime1.getSoundTime());
        return sound;*/

        }


    /**
     * 上传语音文件
     * @param sound
     * @return
     * @throws Exception
     */
    @Override
    public Boolean saveSound(Sound sound) throws Exception {
        try {
            //校验
            if (!ObjectUtil.isAllNotEmpty(sound.getUserId(), sound.getSoundUrl())) {
                return null;
            }

            //设置id
            sound.setId(ObjectId.get());
            sound.setSid(this.idService.createId(IdType.SOUND));

            //发布时间
            sound.setCreated(System.currentTimeMillis());

            //保存到Mongodb中
            this.mongoTemplate.save(sound);

            return sound.getId() != null;
        } catch (Exception e) {
            log.error("语音发布失败~ sound = " + sound, e);
        }
        return false;

        /*if (!ObjectUtil.isAllNotEmpty(sound.getUserId(),sound.getSoundUrl())){
            return null;
        }
        User user= UserThreadLocal.get();
        // 通过redis获取自增的vid
        Long sid=idService.createId(IdType.SOUND);
        System.out.println(sid);
        sound.setSid(this.idService.createId(IdType.SOUND));
        sound.setUserId(user.getId());
        sound.setCreated(System.currentTimeMillis());
        // 将video存入MongoDB
        return this.mongoTemplate.save(sound).getId() != null;*/
    }
}
